<template>
  <!-- 权限管理-权限列表 -->
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑下面卡片主题区域 -->
    <el-card style="width: 100%">
      <!-- 添加分类按钮所在el-row,含对应dialog -->
      <el-row>
        <el-col>
          <!-- 添加分类按钮 -->
          <el-button type="primary" @click="addcate">添加分类</el-button>
          <!-- 添加分类按钮对应的对话框 -->
          <el-dialog
            title="添加分类"
            :visible.sync="addCateDialogVisiable"
            width="50%"
            @close="addCateDialogClose"
          >
            <el-form
              :model="addCateForm"
              status-icon
              ref="addCateFormRef"
              :rules="addCateFormRules"
              label-width="80px"
            >
              <el-form-item label="分类名称" prop="cat_name">
                <el-input v-model="addCateForm.cat_name"></el-input>
              </el-form-item>
              <el-form-item label="父级分类">
                <el-cascader
                  :options="parentCateList"
                  v-model="selectedKeys"
                  clearable
                  :props="{
                    expandTrigger: 'hover',
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children',
                    checkStrictly: true
                  }"
                  @change="handleChange"
                >
                </el-cascader>
              </el-form-item>
            </el-form>

            <span slot="footer">
              <el-button @click="addCateDialogVisiable = false"
                >取 消</el-button
              >
              <el-button type="primary" @click="addCateButton">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <el-table
        :data="cateList"
        border
        stripe
        row-key="cat_id"
        :tree-props="{ children: 'children' }"
        :indent="30"
      >
        <!-- 索引的问题解决不了，就不写了:TODO -->
        <el-table-column prop="cat_name" label="分类名称"> </el-table-column>
        <el-table-column prop="cat_deleted" label="是否有效">
          <template v-slot:default="scope">
            <i
              class="el-icon-circle-check"
              v-if="scope.row.cat_deleted === false"
              style="color:green;"
            ></i>
            <i
              class="el-icon-circle-close"
              style="color:red;"
              v-if="scope.row.cat_deleted === true"
            ></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序">
          <template v-slot:default="scope">
            <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag type="success" v-else-if="scope.row.cat_level === 1"
              >二级</el-tag
            >
            <el-tag type="warning" v-else-if="scope.row.cat_level === 2"
              >三级</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template v-slot:default="scope">
            <el-button type="primary" @click="editCate(scope.row)" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteCate(scope.row)" size="mini"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        title="修改分类"
        :visible.sync="editCateDialogVisiable"
        width="50%"
        @close="editCateDialogClose()"
      >
        <el-form
          :model="editCateForm"
          ref="editCateFormRef"
          status-icon
          :rules="editCateFormRules"
          label-width="80px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editCateDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="editCateOk()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 下面分页显示 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :page-size="queryInfo.pagesize"
        :current-page="queryInfo.pagenum"
        layout="total, prev, pager, next, jumper"
        background
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 添加商品分类的对话框是否显示属性
      addCateDialogVisiable: false,
      // 修改商品分类的对话框是否显示树形
      editCateDialogVisiable: false,
      // 分类列表数据
      cateList: [],
      // 父级(一级和二级)分类列表数据，添加分类对话框中级联选择器要用
      parentCateList: [],
      // getCateList()方法内部请求使用的参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总的商品分类数量
      total: 0,
      // 添加分类,包含cat_pid,cat_name,cat_level
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 修改分类
      editCateForm: {
        cat_id: 0,
        cat_name: ''
      },
      // 级联选择器选中的分类id数组
      selectedKeys: [],
      // 添加分类对话框分类名称验证规则
      addCateFormRules: {
        cat_name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }]
      },
      editCateFormRules: {
        cat_name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 点击添加分类按钮，添加商品分类方法
    addcate () {
      this.getParentCateList()
      this.addCateDialogVisiable = true
    },
    // 重置添加分类的对话框
    addCateDialogClose () {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    // 页面created时调用的获取商品分类数据的方法
    async getCateList () {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.cateList = res.data.result
        this.total = res.data.total
      }
    },
    // 分页显示页码改变,pagenum表示当前页面
    handleCurrentChange (pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getCateList()
    },
    // 编辑分类
    editCate (row) {
      this.editCateDialogVisiable = true
      this.editCateForm.cat_id = row.cat_id
      this.editCateForm.cat_name = row.cat_name
    },
    // 编辑分类对话框点击确认按钮
    editCateOk () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `categories/${this.editCateForm.cat_id}`, { cat_name: this.editCateForm.cat_name })
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
            this.getCateList()
            this.editCateDialogVisiable = false
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
      this.editCateForm.cat_id = 0
      this.editCateForm.cat_name = ''
    },
    // 删除分类
    async deleteCate (row) {
      this.$MessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        // 发送请求，进行删除用户操作
        const { data: res } = await this.$http.delete(`categories/${row.cat_id}`)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          this.getCateList()
        } else {
          this.$message.error(res.meta.msg)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // cascader级联选择器的事件
    handleChange (value) {
      // value和this.selectedKeys相同
      if (this.selectedKeys.length > 0) {
        // 级联选择器有选择东西1:选择了第一级2:选择了第二级
        // 级联选择器选中的父ID
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        // 待添加的分类名称的分类等级
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        // 没有选中东西，默认添加到1级菜单
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 添加分类对话框的确认按钮点击事件
    addCateButton () {
      // 获取分类id，发送(根据id查询分类)获取父id，组成addCateForm{}
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('验证错误')
        } else {
          const { data: res } = await this.$http.post('categories', this.addCateForm)
          if (res.meta.status === 201) {
            this.$message.success('添加分类成功！')
            this.getCateList()
          } else {
            this.$message.error('分类添加失败' + res.meta.msg)
          }
          this.addCateDialogVisiable = false
        }
      })
    },
    // 获取父级分类(一级和二级)的数据列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.parentCateList = res.data
      }
    },
    // 修改分类对话框关闭
    editCateDialogClose () {
      this.editCateDialogVisiable = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
